<template>
    <div class="dh_putin">
        <div class="dh_p-content">
            <!-- 查询 -->
            <div class="dh_p-c-inquire">

                <el-form :model="putinform" ref="purinform" :inline="true" label-width="60px" class="dh_pci-form mb10 pl10 pr10">
                    <el-form-item label="查询项" class="mt20 mb20">
                        <el-select v-model="putinform.select" @change=";for(var r in putinform) r != 'select' ? putinform[r] = '' : ''">
                            <el-option label="员工ID" value="1"></el-option>
                            <el-option label="申请状态" value="2"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="员工ID" v-if="putinform.select == 1" class="mt20 mb20">
                        <el-input v-model="putinform.staffid" placeholder="请输入查询的员工工号"></el-input>
                    </el-form-item>

                    <el-form-item label="查询项" v-else class="mt20 mb20">
                        <el-select v-model="putinform.applystate" placeholder="选择查询对应的状态">
                            <el-option label="申请中" value="0"></el-option>
                            <el-option label="已同意" value="1"></el-option>
                            <el-option label="已拒绝" value="2"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item class="mt20 mb20">
                        <el-button type="primary" @click="seekputin" class="p10 f18">查询</el-button>
                        <el-button type="danger" @click="requestputin();for(var r in putinform) r != 'select' ? putinform[r] = '' : ''" class="p10 f18">取消查询</el-button>
                    </el-form-item>
                </el-form>

            </div>
            <!-- 列表数据 -->
            <div class="dh_p-c-list">
                <table class="dh_pcl-table tc f14">
                    <thead>
                        <tr>
                            <th>申请表ID</th>
                            <th>申请员工</th>
                            <th>申请时间</th>
                            <th>申请理由</th>
                            <th>申请状态</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="(item,key) in putinlist" :key="key">
                            <td>{{item.id}}</td>
                            <td>{{item.staffid | filtername}}</td>
                            <td>{{item.applytime*1000 | formatDate}} {{item.applytime*1000 | formatDateBehind}}</td>
                            <td>{{item.reason}}</td>
                            <td>
                                <!-- <button type="button" @click="updataputin(item.id,key,1)" class="bc4a wh pt5 pr10 pb5 pl10 br5 f16">同意</button> -->
                                
                                <span><span v-if="item.applystate == 1">{{item.applystate | applystate}}</span><button v-else type="button" @click="updataputin(item,key,1)" class="bc4a wh pt5 pr10 pb5 pl10 br5 f16">同意</button></span>
                                <span><span v-if="item.applystate == 2">{{item.applystate | applystate}}</span><button v-else type="button" @click="updataputin(item,key,2)" class="bcfd wh pt5 pr10 pb5 pl10 br5 f16">拒绝</button></span>
                            </td>
                        </tr>
                    </tbody>
                </table>

                <!-- 分页 -->
                <div class="dh_pcl-block bt1">
                    <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page.sync="currentPage"
                    :page-sizes="[5, 10, 15, 20]"
                    :page-size="pagesize"
                    layout="total, sizes, prev, pager, next"
                    :total="total"
                    class=" pt5 pr10 pb5 pl10">
                    </el-pagination>
                </div>
            </div>

        </div>

    </div>
</template>

<script>
const axios = require('axios');
import {formatDate} from '../js/time.js'
let that
export default {
    components: {},
    data() {
        return {
            token: '',
            putinlist: [],
            // 查询的form表单绑定值
            putinform: {
                select: '1',
                staffid: '',
                applystate: ''
            },
            pageingstate: 0,                    //彩笔使用的分页状态管理（区分数据运行）
            currentPage: 1,						//分页的默认页数
            pagesize: 10,                       //单页条数
            total: 0,						   //总条数
            staffname: ''                      //员工姓名
        };
    },
    filters: {
        // 转化申请状态
        applystate(state){
            if(state === 1){
                state = "已同意"
            }else{
                state = "已拒绝"
            }
            return state
        },
        // 使用过滤器转化时间戳
        formatDate(time){
            var date = new Date(time);
            return formatDate(date, 'yyyy-MM-dd')
        },
        formatDateBehind(time){
            var date = new Date(time);
            return formatDate(date, 'hh:mm:ss')
        },
        // 过滤员工姓名
        filtername(staffid ){
            that.staffname.forEach((item)=>{
                if(staffid  === item.id){
                    staffid = item.name;
                }
            })
            return staffid
        }
    },
    computed: {},
    watch: {},
    methods: {
        // 请求列表数据
        async requestputin(){
            let that = this;
            let data = {current:that.currentPage,size:that.pagesize};
            let updata = JSON.stringify(data);
            await axios({
                method: 'post',
                url: '/api/apply/list',
                headers:{
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                },
                data: updata
            })
            .then( resp=> {
                // console.log(resp)
                that.pageingstate = 0;
                that.putinlist = resp.data.data
                that.total = resp.data.code;
            })
            .catch( err=> {})
        },

        // 分页的函数
        handleSizeChange(val) {
            // console.log(`每页 ${val} 条`);
            let that = this;
            that.pagesize=val
            if(that.pageingstate === 0){
                that.requestputin()
            }else{
                that.seekputin()
            }
        },
        handleCurrentChange(val) {
            // console.log(`当前页: ${val}`);
            let that = this;
            that.currentPage=val
            // console.log(that.currentPage)
            if(that.pageingstate === 0){
                that.requestputin()
            }else{
                that.seekputin()
            }
        },

        // 查询搜索
        seekputin(){
            let that = this;
            if(Number(that.putinform.select) === 1 && that.putinform.staffid == ''){
                return that.$message({
                    showClose:true,
                    message: '员工号不能为空',
                    type: 'warning'
                })                
            }else if(Number(that.putinform.select) === 2 && that.putinform.applystate == ''){
                return that.$message({
                    showClose:true,
                    message: '申请状态不能为空',
                    type: 'warning'
                })              
            }else{
                let data = {
                    current:that.currentPage,
                    size:that.pagesize,
                    staffid:that.putinform.staffid, 
                    applystate:that.putinform.applystate
                };
                for(var i in data)
                data[i] === '' ? delete data[i] : ''
                let updata = JSON.stringify(data);
                // console.log(updata)
                axios({
                method: 'post',
                url: '/api/apply/list',
                headers:{
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                },
                data: updata
                })
                .then( resp=> {
                    // console.log(resp)
                    that.pageingstate = 1;
                    that.putinlist = resp.data.data
                    that.total = resp.data.code;
                })
                .catch( err=> {})
            }
        },

        // 同意或者拒绝
        async updataputin(item,key,num){
            let that = this;
            let data,api,i;
            await that.$confirm(num == 1?"该操作可能会导致后台数据被他人篡改":"是否确认拒绝?",num == 1?'同意员工的权限申请':'拒绝后员工的权限申请',{
                confirmButtonText: '确定',
                cancelButtinText: '取消',
                type: 'warning',
                center: true
            }).then(() => {
                i=0
                that.$message({
                    type: 'success',
                    message: '操作成功'
                })
            }).catch(() => {
                i=2
                that.$message({
                    type: 'info',
                    message: '已取消'
                })
            })

            for(i;i<2;i++){
                if(i === 0){
                    data = {id:item.id,applystate:num}
                    api = '/api/apply/update'
                }else{
                    data = {
                        id:item.staffid,
                        manage:num!==1? 0 : num
                    }
                    api = '/api/staff/update'
                }
                let updata = JSON.stringify(data)

                await axios({
                    method: 'post',
                    url:api,
                    headers:{
                        'Content-Type': 'application/json',
                        'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                    },
                    data: updata
                }).then( resp=>{
                    // console.log(resp)
                    if(i === 0){
                        that.putinlist[key].applystate = num
                    }else{return}                        
                }).catch( err=> {})
            }
        },

        // 全部员工姓名
        async requestname(){
            let that = this;
            let total = 10,select;
            for(var i=0;i<2;i++){
                let that = this;
                let data = {current:1,size:total};
                let updata = JSON.stringify(data);
                // console.log(updata)
                await axios({
                    method: 'post',
                    url: '/api/staff/list',
                    headers: {
                        'Content-Type': 'application/json',
                        'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                    },
                    data: updata
                }).then(resp=>{
                    // console.log(resp)
                    if(i === 0){
                        resp.data.code <= 10 ? (
                            that.staffname = resp.data.data.map((item)=>{
                                return {
                                    id: item['id'],
                                    name: item['name']
                                }
                            }),i = 2,that.requestputin()
                        ) : total = resp.data.code;
                    }else{
                        that.staffname = resp.data.data.map((item)=>{
                            return {
                                id: item['id'],
                                name: item['name']
                            }
                        })
                        that.requestputin()
                    }
                }).catch(err=>{})
            }
            // console.log(that.staffname,that.putinlist)
        },

        async requesttoken(){
            let loguser = JSON.parse(sessionStorage.getItem('updata'))
            let data = {username:loguser.username, password:loguser.password};
            let updata = JSON.stringify(data);
            // console.log(updata)
            await axios({
                method: 'post',
                url: '/api/getAuthority/manager',
                headers: { 'Content-Type': 'application/json' },
                data: updata
            })
            .then( resp=> {
                // console.log(resp)
                this.token = resp.data.data;
                sessionStorage.setItem('token',JSON.stringify(resp.data.data))
                this.requestname()
            }).catch( err=> {})
        }
    },
    created() {
        this.requesttoken()
    },
    mounted() {
        let that = this;
        // this.one()
        // that.token = JSON.parse(sessionStorage.getItem('token'))
        // console.log('1',that.token)
    },
    beforeCreate() {
        that = this;
    },
    beforeMount() {},
    beforeUpdate() {},
    updated() {},
    beforeDestroy() {},
    destroyed() {},
    activated() {},
    }
</script>
<style scoped>
.dh_putin{
    height: 100%;
}
.dh_p-content{
    height: 100%;
}
/* 查询 */
.dh_pci-form{
    background-color: #ffffff;
    border-radius: 5px;
    box-shadow: 0 0 2px #4b4b4b;
}
/* 列表数据 */
.dh_p-c-list{
    display: flex;
    flex-direction: column;
    height: calc(100% - 91px);
    padding: 10px;
    background-color: #ffffff;
    border-radius: 5px;
    box-shadow: 0 0 2px #4b4b4b;
    box-sizing: border-box
}
.dh_pcl-table{
    width: 100%;
    border-collapse: collapse;
    border-bottom: 1px solid #e0e0e0;
    border-right: 1px solid #e0e0e0;
    border-spacing: 0;/*去掉单元格间隙*/
}
.dh_pcl-table th{
    background-color: #ececec;
}
.dh_pcl-table tbody tr:hover{
    background-color: #ececec;
}
.dh_pcl-table th,.dh_pcl-table td{
    padding: 10px 0;
    border-left:1px solid #e0e0e0;
    border-top:1px solid #e0e0e0;
}
/* 分页 */
.dh_pcl-block{
    margin-top: auto;
}
</style>